<template>
  <div class="editor">
    <quill-editor 
      ref="myTextEditor"
      v-model="contentValue"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @ready="onEditorReady($event)"
      @change="onEditorChange($event)"
      class="cfpa-quill-editor"
    >
    </quill-editor>
    <!-- <div :style="wordCount" v-if="wordCount" class="cfpa-quill-wordCount">
      <div class="cfpa-quill-wordCount-text">当前已经输入<span style="color: red">{{contentLength}}</span>个字符</div>
    </div> -->
     <el-upload
      class="avatar-uploader"
      action=""
      ref="upload"
      :show-file-list="false"
      :http-request="upload"
      style="display:none"
      >
    </el-upload>
  </div>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { Quill, quillEditor } from 'vue-quill-editor'
import { uploadFile } from './../../server/getDate'

// 图片可收缩
import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)

// 自定义字体大小
let Size = Quill.import('attributors/style/size')
Size.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '30px', '32px', '36px']
Quill.register(Size, true)

// 自定义字体类型
var fonts = ['SimSun', 'SimHei','Microsoft-YaHei','KaiTi','FangSong','Arial','Times-New-Roman','sans-serif'];  
var Font = Quill.import('formats/font')
Font.whitelist = fonts // 将字体加入到白名单
Quill.register(Font, true)

export default {
  name: 'editor',
  components: {
    quillEditor,
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    editorHeight: {
      type: Number,
      default: 355
    },
    editorWordCount: {
      type: Number,
      default: 0
    },
    htmlContent: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      fullscreenLoading: false,
      contentValue: '',
      preContent: '',
      dialogFnOpenUpload: false,
      accept: '',
      uploadType: '',
      fileType: '1',
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
              ['blockquote', 'code-block'],
              [{'header': 1}, {'header': 2}],               // custom button values
              [{'list': 'ordered'}, {'list': 'bullet'}],
              [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
              [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
              [{'direction': 'rtl'}],                         // text direction
              [{'size': [false, '10px', '12px', '14px', '16px', '18px', '20px', '24px', '30px', '32px', '36px'] }],  // custom dropdown
              [{'header': [1, 2, 3, 4, 5, 6, '段落']}],
              [{'color': []}, {'background': []}],          // dropdown with defaults from theme
              [{'font': fonts}],
              [{'align': []}],
              ['link', 'image', 'video'],
              ['clean']                          // remove formatting button
            ],
              handlers: {
                'image': function (value) {
                  if (value) {
                    this.fileType = '1'
                    this.uploadType = 'image'
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.editor.format('image', false);
                  }
                },
                'video': function (value) {
                  console.log(value)
                  if (value) {
                    this.fileType = '3'
                    this.uploadType = 'video'
                     document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.editor.format('image', false);
                  }
                },
              }
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
          }
        },
        placeholder: '请编写内容...'
      },
      data_extra: {
        parentId: 0,
        fileName: ''
      },
      contentLength: 0,
      wordCount: '',
      title: '添加图片',
      // quillEditorHeight: 500
    }
  },
  computed: {
    editor () {
      return this.$refs.myTextEditor.quill
    }
  },
  methods: {
    /**
     * @description [onEditorBlur 失去焦点]
     * @author   zoumiao
     * @param {Object} editor 返回的quill对象
     * @return   {null}   [没有返回]
     */
    onEditorBlur (editor) {
      this.$emit('editorBlur')
    },
    /**
     * @description [onEditorFocus 获取焦点]
     * @author   zoumiao
     * @param {Object} editor 返回的quill对象
     * @return   {null}   [没有返回]
     */
    onEditorFocus (editor) {
      this.$emit('editorFocus')
    },
    /**
     * @description [onEditorReady 可以输入]
     * @author   zoumiao
     * @param {Object} editor 返回的quill对象
     * @return   {null}   [没有返回]
     */
    onEditorReady (editor) {
    },
    /**
     * @description [onEditorChange 输入文本改变事件]
     * @author   zoumiao
     * @param {Object} editor 返回的编辑对象{html, text, quill}
     * @return   {null}   [没有返回]
     */
    onEditorChange (editor) {
      let html = editor.html
      this.preContent = html
      this.$emit('input', html)
      this.contentLength = editor.text.trim().length
    },
    /**
     * [fnOpenUploadSubmit 提交上传文件]
     * @author   zoumiao
     * @return   {null}   [没有返回]  
     */
    upload(value) {
      let formData = new FormData()
      formData.append('fileName', value.file);
      formData.append('fileType', this.fileType)
      uploadFile(formData, res => {
          if (res.code === '000000') {
              this.editor.focus()
              this.fullscreenLoading = false
              let url = res.result.storageName
              if (url != null && url.length > 0) {
                // if (this.uploadType === 'image') {
                // } else {
                //   this.contentValue = this.contentValue + `<iframe frameborder="0" width="320" height="480" src=${url} allowfullscreen></iframe>`
                // }
                let length = this.editor.getSelection().index
                console.log(this.editor)
                this.editor.insertEmbed(length, 'image', url)
                this.editor.setSelection(length + 1)
              } else {
                this.$message.error(`${this.uploadType}插入失败`)
              }
              this.$refs['upload'].clearFiles()
          } else {
              this.$message.error(res.message)
          }
      })
    },
  },
  created () {
    this.contentValue = this.value
    this.contentValue = this.htmlContent
    this.contentLength = this.editorWordCount || 0
  },
  mounted () {
    let toolbar = document.querySelector('div.ql-toolbar.ql-snow')
    if (toolbar) {
      let toolbarHeight = toolbar.offsetHeight
      this.wordCount = {
        'top': `${toolbarHeight}px`
      }
      return
    }
    this.wordCount = {
      'top': '42px'
    }
  },
  watch: {
    // Watch content change
    value (newVal, oldVal) {
      if (newVal && newVal !== this.preContent) {
        this.preContent = newVal
        this.contentValue = newVal
      } else if (!newVal) {
        this.contentValue = ''
      }
    },
    htmlContent (newVal, oldVal) {
      if (newVal && newVal !== this.preContent) {
        this.preContent = newVal
        this.contentValue = newVal
      } else if (!newVal) {
        this.contentValue = ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cfpa-quill-editor {
  line-height: 24px;
  .ql-snow {
    background-color: #ffffff;
  }
}
.cfpa-quill-wordCount {
  .cfpa-quill-wordCount-text{
    text-align: right;
    margin-right: 10px;
    color: #aaa;
  }
}
</style>